package com.mot.j2me.midlets;																		


import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;  
import java.io.*;

import javax.microedition.io.*;

public class Login extends MIDlet implements CommandListener {
    
	TextField Pin=null;
	TextField Location=null;
	Form authForm, mainscreen;
	TextBox t = null;
	StringBuffer b = new StringBuffer();
    Display myDisplay = null;
    private StringItem si = new StringItem("","");
    private String IMEI = "0123456789";
    private Command okCommand = new Command("OK", Command.OK, 1);
    private Command exitCommand = new Command("Exit", Command.EXIT, 2);
    private Command backCommand = new Command("Back", Command.BACK, 2);
    private Alert alert = null;

    public Login() {        

    myDisplay = Display.getDisplay(this);
    Pin=new TextField("Enter Pin:","",10,TextField.ANY);
	//Location=new TextField("Location","",10,TextField.ANY);
	authForm=new Form("Identification");
	mainscreen=new Form("");
	authForm.append(Pin);
	authForm.addCommand(okCommand);
	authForm.addCommand(exitCommand);
	authForm.setCommandListener(this);
	myDisplay.setCurrent(authForm);

    }
    
    
    public void displayString(String string)
    {
    	//form.append(si);
    	si.setText(string);
        
    }

    public void startApp() throws MIDletStateChangeException { 
    }

    public void pauseApp() {
    }


  
    protected void destroyApp(boolean unconditional)
            throws MIDletStateChangeException {
    }

  
    public void commandAction(Command c, Displayable d) {
        
	    if (c == okCommand) {
			if (Pin.getString().equals("") ){
				alert = new Alert("Error", "Pin cannot be blank", null, AlertType.ERROR);
				alert.setTimeout(Alert.FOREVER);
				myDisplay.setCurrent(alert);
			}
			else{
				mainscreen.deleteAll();
				mainscreen.append(si);
				si.setText("Logging in....");
				mainscreen.addCommand(backCommand);
				mainscreen.addCommand(exitCommand);
				mainscreen.setCommandListener(this);
			    myDisplay.setCurrent(mainscreen);
				Ret ret = new Ret(this, Pin.getString(), IMEI);
	            ret.start();
	        
				
			}
		}
	   
	     if (c == backCommand) {
	    	Pin.setString("");
	    	myDisplay.setCurrent(authForm);
		}
		
	    if (c == exitCommand) {
			notifyDestroyed();
		}
	}
        
   
} 




class Ret extends Thread {
    
	private Login midlet;
 //   private String errorMsg = null;
    String pin, query, IMEI;
     public Ret(Login login, String pin, String IMEI){
        
    	 /**
          * Constructor
          *
          * EFFECTS: Initialise the server and store midlet information
          * @param midlet The main application midlet
          * @param server Forecast Server URL
          */
    	 
        this.midlet = login;
        this.pin = pin;
        this.IMEI = IMEI;
        System.out.println(pin);
        
    }


    public void run(){
            /**
            * Entry point of the thread
            * EFFECTS: call to connect() method
            */
        
    	try {
    		   //Thread.sleep(000);
               //String locString = "";
               //locString = checkLocation();
               //put a new method which is check deals
               
        	   Authenticate(pin, IMEI);
           
               
            } catch (Exception ex){
               ex.printStackTrace();

               
            }
            
        }
    
   
    
    public void Authenticate(String Pin, String IMEI) {
		long endTime, startTime = System.currentTimeMillis();
		long time;
		String param1= "IMEI="+IMEI;
		param1+="&PassWord="+Pin;
		String str = loadURL(param1);
		// t = new TextBox("Reply",b.toString(),1024,0);
		
		midlet.b.setLength(0);
		midlet.b.append("\n");
		midlet.b.append(str);
		midlet.mainscreen.append(midlet.b.toString());
		endTime = System.currentTimeMillis();
		time = endTime - startTime;
		midlet.displayString("Load time is " + Long.toString(time) + "ms");
		midlet.myDisplay.setCurrent(midlet.mainscreen);
	}

	public String loadURL(String query){
		String URL   = "http://mlbs.no-ip.org:8080/MLBSWebApp/MlbsServlet"+"?"+query;
    	URL = urlEncoder(URL);
    	System.out.println("URL:"+URL);
    
		HttpConnection c = null;
		InputStream is = null;
		try {
		  System.out.println("In XXXX .....\n\n");
		  c = (HttpConnection)Connector.open(URL);	
		  c.setRequestMethod(HttpConnection.GET);
		  is = c.openInputStream();
		  
		  ///////////
		  if (c.getResponseCode() == HttpConnection.HTTP_OK)
		  {
		        int length = (int) c.getLength();
		        String str;
		        if (length != -1){
		          byte servletData[] = new byte[length];
		          is.read(servletData);
		          str = new String(servletData);
		          System.out.println("server response:"+str);
		          return str;
		        }else  // Length not available...
		        {
		          ByteArrayOutputStream bStrm = new ByteArrayOutputStream();
		          
		          int ch;
		          while ((ch = is.read()) != -1){
		            bStrm.write(ch);
		          }
		          str = new String(bStrm.toByteArray());
		          bStrm.close();
		        }
		        System.out.println("server response2:"+str);
		        return str;
		   
		  }
		  //////////
		}catch (Exception e) {
			// TODO: handle exception
		}finally {
			          try {
						is.close();
						c.close();
					} catch (Exception e) {
						
					}
			  }
		return null;
		} 
	
 	public static String urlEncoder(String s) {
 		if (s == null)
 			return s;
 		s=s.replace(' ' , '+');
 		return s;
 	}
	

}